/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.jena.query.spatial;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.jena.atlas.iterator.Iter;
import org.apache.jena.atlas.iterator.Transform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.graph.impl.LiteralLabel;
import com.hp.hpl.jena.sparql.core.Quad;
import com.hp.hpl.jena.sparql.core.QuadAction;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.context.jts.JtsSpatialContext;
import com.spatial4j.core.shape.Shape;

public class SpatialDocProducerTriples implements SpatialDocProducer {
	private static Logger log = LoggerFactory
			.getLogger(SpatialDocProducerTriples.class);
	private final EntityDefinition defn;
	private final SpatialIndex indexer;
	private boolean started = false;

	private Map<String, Set<SpatialPredicatePairValue>> spatialPredicatePairValues = new HashMap<String, Set<SpatialPredicatePairValue>>();

	/**
	 * The Spatial4j {@link SpatialContext} is a sort of global-ish singleton
	 * needed by Lucene spatial. It's a facade to the rest of Spatial4j, acting
	 * as a factory for {@link Shape}s and provides access to reading and
	 * writing them from Strings.
	 */
	private SpatialContext ctx = JtsSpatialContext.GEO;// "ctx" is the
														// conventional
														// variable name

	public SpatialDocProducerTriples(EntityDefinition defn, SpatialIndex indexer) {
		this.defn = defn;
		this.indexer = indexer;
	}

	@Override
	public void start() {
		indexer.startIndexing();
		started = true;
	}

	@Override
	public void finish() {
		indexer.finishIndexing();
	}

	@Override
	public void change(QuadAction qaction, Node g, Node s, Node p, Node o) {
		// One document per triple/quad

		if (qaction != QuadAction.ADD)
			return;

		if (!o.isLiteral()) {
			return;
		}

		String x = (s.isURI()) ? s.getURI() : s.getBlankNodeLabel();

		if (defn.isSpatialPredicate(p) && isDecimal(o.getLiteral())) {

			boolean isLat = defn.isLatitudePredicate(p);

			SpatialPredicatePair pair = defn.getSpatialPredicatePair(p);
			Set<SpatialPredicatePairValue> pairValues = spatialPredicatePairValues
					.get(x);
			if (pairValues == null) {
				pairValues = new HashSet<SpatialPredicatePairValue>();
				spatialPredicatePairValues.put(x, pairValues);
			}

			Iterator<SpatialPredicatePairValue> it = pairValues.iterator();
			SpatialPredicatePairValue toRemove = null;

			while (it.hasNext()) {
				SpatialPredicatePairValue pairValue = it.next();
				if (pairValue.getPair().equals(pair)) {
					Double theOtherValue = pairValue.getTheOtherValue(p);
					if (theOtherValue != null) {
						if (isLat) {
							indexer.add(x, ctx.makePoint(theOtherValue, Double
									.parseDouble(o.getLiteralLexicalForm())));
						} else {
							indexer.add(x, ctx.makePoint(Double.parseDouble(o
									.getLiteralLexicalForm()), theOtherValue));
						}
						toRemove = pairValue;
					}
					break;
				}
			}
			if (toRemove != null) {
				pairValues.remove(toRemove);
				return;
			}

			SpatialPredicatePairValue toAdd = new SpatialPredicatePairValue(
					pair);
			toAdd.setValue(p, Double.parseDouble(o.getLiteralLexicalForm()));
			pairValues.add(toAdd);

		} else if (defn.isWKTPredicate(p) && isWKTLiteral(o.getLiteral())) {

			Shape shape = this.ctx.readShape(o.getLiteralLexicalForm());
			indexer.add(x, shape);
		}

	}

	static Transform<Quad, Triple> QuadsToTriples = new Transform<Quad, Triple>() {
		@Override
		public Triple convert(Quad item) {
			return item.asTriple();
		}

	};

	static private List<Triple> quadsToTriples(List<Quad> quads) {
		return Iter.map(quads, QuadsToTriples);
	}

	private boolean isDecimal(LiteralLabel literal) {
		RDFDatatype dtype = literal.getDatatype();
		if (dtype == null){
			try {
				Double.parseDouble(literal.getLexicalForm());
				return true;
			} catch(NumberFormatException e){
				return false;
			}
		}
		if ((dtype.equals(XSDDatatype.XSDfloat))
				|| (dtype.equals(XSDDatatype.XSDdecimal))
				|| (dtype.equals(XSDDatatype.XSDdouble) || (dtype
						.equals(XSDDatatype.XSDinteger))))
			return true;
		return false;
	}

	private boolean isWKTLiteral(LiteralLabel literal) {
		RDFDatatype dtype = literal.getDatatype();
		if (dtype == null)
			return false;
		if (dtype.getURI().equals(
				EntityDefinition.geosparql_wktLiteral.getURI()))
			return true;
		return false;
	}
}
